﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ACC.Data.Entities.Common
{
    public class GuidOracle
    {
        public static string RAWTOHEX(byte[] b)
        {
            StringBuilder sb = new StringBuilder();
            foreach (byte by in b)
            {
                string s = Convert.ToString(by, 16);//将字节转换成对应的字符  
                if (s.Length == 1)
                {
                    s = "0" + s;//当字符不足两位时，在前面补0，补足两位字符，因为字符串“01”转换成的字节为1，而将字节再转换成字符串的时候就变成了“1”，因此要补0  
                }
                sb.Append(s);
            }
            return sb.ToString().ToUpper();
        }

        public static byte[] HEXTORAW(string str)
        {
            if (str.Length % 2 == 0)
            {
                byte[] b = new byte[str.Length / 2];
                int j = 0;
                for (int i = 0; i < str.Length; i += 2)
                {
                    byte by = Convert.ToByte(str.Substring(i, 2), 16);//取两个字符，转换成对应的字节  
                    b[j] = by;
                    j++;
                }
                return b;
            }
            else
            {
                throw new Exception("不能将该字符串转换成RAW类型");
            }
        }

        public static string OracleToDotNet(string text)
        {
            byte[] bytes = ParseHex(text);
            Guid guid = new Guid(bytes);
            return guid.ToString("N").ToUpperInvariant();
        }

        public static string DotNetToOracle(string text)
        {
            Guid guid = new Guid(text);
            return BitConverter.ToString(guid.ToByteArray()).Replace("-", "");
        }

        static byte[] ParseHex(string text)
        {
            // Not the most efficient code in the world, but
            // it works...
            byte[] ret = new byte[text.Length / 2];
            for (int i = 0; i < ret.Length; i++)
            {
                ret[i] = Convert.ToByte(text.Substring(i * 2, 2), 16);
            }
            return ret;
        }
    }
}
